package com.mc.moring.main.loan

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gyf.immersionbar.ImmersionBar
import com.mc.moring.BafBase.BAFBaseActivity
import com.mc.moring.R
import com.mc.moring.app.LogUtils
import com.mc.moring.base.HttpCallback
import com.mc.moring.bean.AppConfigBean
import com.mc.moring.bean.AppConfigBeanData
import com.mc.moring.bean.BankAccountListBean
import com.mc.moring.bean.CreditGetResultBean
import com.mc.moring.bean.LoanCalLoanDataBean
import com.mc.moring.bean.LoanInfoVo
import com.mc.moring.bean.LoanInfoVoChild
import com.mc.moring.bean.SingleSelectBean
import com.mc.moring.bean.WebLinkBean
import com.mc.moring.main.WebViewActivity
import com.mc.moring.main.modle.LoanModle
import com.mc.moring.main.modle.MianModle
import com.mc.moring.main.modle.PermisosModle
import com.mc.moring.util.GsonUtils
import com.mc.moring.util.PointMgr
import com.mc.moring.util.SPUtils
import com.mc.moring.util.SharePreUtil
import com.mc.moring.util.StringUtils
import com.mc.moring.util.ZhiliDeviceUtils
import com.mc.moring.util.ext.StringExt.extFormatMoney
import com.mc.moring.widge.JDialogCallback
import com.mc.moring.widge.JVipDialog
import com.mc.moring.widge.LoanRetentionDialog
import com.mc.moring.widge.NumberView
import com.mc.moring.widge.SingleSelectBankDialogView
import com.mc.moring.widge.SingleSelectMomenyDialogView
import com.mc.moring.widge.SingleSelectMomenyDialogView.SingleSelectListener
import com.mc.moring.widge.SingleSelectProductDialogView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Calendar
import java.util.Date
import kotlin.collections.set


/**
 * loan page
 * author: Created by nao on 2018-10-15
 * version: 1.0.0
 */
class MLoanActivity : BAFBaseActivity<MLoanActivity>() {

    private val abBackIBtn by lazy { findViewById<ImageButton>(R.id.abBackIBtn) }
    private val recyclerView by lazy { findViewById<RecyclerView>(R.id.recyclerView) }
    private val tv_have_money by lazy { findViewById<TextView>(R.id.tv_have_money) }
    private val tv_total_money by lazy { findViewById<TextView>(R.id.tv_total_money) }
    private val tv_lixi by lazy { findViewById<TextView>(R.id.tv_lixi) }
    private val tv_money by lazy { findViewById<NumberView>(R.id.tv_money) }
    private val tv_date by lazy { findViewById<TextView>(R.id.tv_date) }
    private val tv_total_date_money by lazy { findViewById<TextView>(R.id.tv_total_date_money) }
    private val rvVoList by lazy { findViewById<RecyclerView>(R.id.rvVoList) }
    private val tv_account_bank by lazy { findViewById<TextView>(R.id.tv_account_bank) }
    private val btn_confirm by lazy { findViewById<TextView>(R.id.btn_confirm) }
    private val iv_edit by lazy { findViewById<ImageView>(R.id.iv_edit) }
    private val tv_mas by lazy { findViewById<TextView>(R.id.tv_mas) }
    private val ll_all_money by lazy { findViewById<LinearLayout>(R.id.ll_all_money) }
    private val ll_all_money_tips by lazy { findViewById<LinearLayout>(R.id.ll_all_money_tips) }
    private val fl_top_tips by lazy { findViewById<FrameLayout>(R.id.fl_top_tips) }
    private val fl_one_tips by lazy { findViewById<FrameLayout>(R.id.fl_one_tips) }
    private val fl_two_tips by lazy { findViewById<FrameLayout>(R.id.fl_two_tips) }
    private val tv_one_hide by lazy { findViewById<TextView>(R.id.tv_one_hide) }
    private val tv_two_hide by lazy { findViewById<TextView>(R.id.tv_two_hide) }
    private val tv_terminos by lazy { findViewById<TextView>(R.id.tv_terminos) }
    private val tv_politica by lazy { findViewById<TextView>(R.id.tv_politica) }
    private  val tv_tips_money by lazy { findViewById<TextView>(R.id.tv_tips_money) }
    private val cb by lazy { findViewById<CheckBox>(R.id.cb) }
    private val tv_loan_tip_day by lazy { findViewById<TextView>(R.id.tv_loan_tip_day) }
    private val tv_loan_tip_money by lazy { findViewById<TextView>(R.id.tv_loan_tip_money) }
    private val tip_framelayout by lazy { findViewById<FrameLayout>(R.id.tip_framelayout) }
    private val tip_framelayout2 by lazy { findViewById<LinearLayout>(R.id.tip_framelayout2) }
    private val tip_framelayout3 by lazy { findViewById<LinearLayout>(R.id.tip_framelayout3) }

    var duracionPrestamoAdapter: DuracionPrestamoAdapter? = null
    var mianModle: MianModle? = null
    var loanModle: LoanModle? = null
    var duracionPrestamoList: MutableList<CreditGetResultBean.DataBean.ProductInfoListBean> =
        ArrayList()

    var duracionPrestamoShowList: MutableList<CreditGetResultBean.DataBean.ProductInfoListBean> =
        ArrayList()

    var loanInfoVoListAdapter: LoanInfoVoListAdapter? = null;
    var loanInfoVoList: MutableList<LoanInfoVo> = ArrayList()

    var loanRetentionDialog: LoanRetentionDialog? = null
    var time: String = ""
    var money: String = ""
    var getCanApply: Boolean = false
    var masChoose:Boolean = false

    var preReqId: String = ""
    var phone: String = ""


    interface OnItemClickListener {
        fun onItemClick(itemWidth: String?, itemHeight: String?)
    }


    private fun changeDate(date: String): String{
        var char: Char
        var finString = StringBuffer()
        var stringShow: String
        for ( index in 8..9 ){
            char = date.get(index)
            finString.append(char)
        }
        finString.append("-")
        for ( index in 5..6 ){
            char = date.get(index)
            finString.append(char)
        }
        finString.append("-")
        for ( index in 0..3 ){
            char = date.get(index)
            finString.append(char)
        }
        stringShow = finString.toString()
        return stringShow
    }

    override fun initLayout(): Int = R.layout.activity_m_loan

    override fun initParameter(bundle: Bundle?) {
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
    }

    override fun afterInjectView() {
        LogUtils.logE("loan page")
        PointMgr.sendEvent("cl_credit_result_page_yes")
        Log.e("PointMgr.INSTANCE.sendEvent", "cl_credit_result_page_yes")
        var intent = intent
        preReqId = intent.getStringExtra("reqId").toString()
        phone = intent.getStringExtra("phone").toString()
        val tryLoanMoney = true
        SharePreUtil.saveStringData("tryLoanMoney",tryLoanMoney.toString())
        var creditGetResultBean = result
        var data2 = creditGetResultBean?.getData()
        var dataBean = GsonUtils.getGson().toJson(data2)
        Log.e("----data2", dataBean)
        var dataList = data2?.productInfoList
        if (dataList != null) {
            val thread = Thread{
                val params: MutableMap<String, String> = java.util.HashMap()
                try {
                    params["productId"] = dataList.get(0).productId.toString()
                    params["applyAmount"] = (dataList.get(0).totalLimitDays*1000).toString()
                    params["groupId"] = dataList.get(0).groupId.toString()
                    params["reqId"] = preReqId
                    params["productIndex"] = dataList.get(0).productIndex.toString()
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
                Log.e("===productId",dataList.get(0).productId.toString())
                Log.e("===applyAmount",(dataList.get(0).totalLimitDays*1000).toString())
                Log.e("===groupId",dataList.get(0).groupId.toString())
                Log.e("===reqId",preReqId)
                Log.e("===productIndex",dataList.get(0).productIndex.toString())

                loanModle?.loancalLoan(params, object : HttpCallback {
                    @RequiresApi(Build.VERSION_CODES.O)
                    override fun onSuccess(data: String) {
                        try {
                            var dataBean =
                                GsonUtils.getGson().fromJson(data, LoanCalLoanDataBean::class.java)

                            Log.e("----dataloan",data)
                            var wrongList = GsonUtils.getGson().toJson( dataBean.data.loanInfoVoList.get(0))
                            Log.e("===wrongList",wrongList)
                            time = dataBean.data.loanInfoVoList.get(0).dueDate
                            money = StringUtils.formatNumberWithCommas(dataBean.data.loanInfoVoList.get(0).totalRepayAmount.toString())
                            Log.e("----time",time)
                            Log.e("----money",money)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }

                    override fun onFaill(e: String) {
                    }
                })
            }
            thread.start()
        }
        mianModle = MianModle.instant
        loanModle = LoanModle.instant

        initEvent()
        initRecycler();
        InitLoad()

        loanRetentionDialog = LoanRetentionDialog(this@MLoanActivity)
        loanRetentionDialog?.setDialogViewOnClickListener(object : LoanRetentionDialog.DialogViewOnClickListener{
            override fun onClickConfirm() {

            }

            override fun onClickCancel() {
                finish()
            }

        })

        btn_confirm.setOnClickListener {
            if (cb.isChecked) {
//                var amount = convertThousandSeparatorToDouble(tv_money.text.toString()).toString()
                PointMgr.sendEvent("cl_sutbmit_loan_2")
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_sutbmit_loan_2")
                loanapplyLoan(tv_money.getAmount().toString())
            }
        }
        iv_edit.setOnClickListener {
            if (selectProduct == null) {
                return@setOnClickListener
            }
            val showMoney = tv_money.getAmount()
            var showMoneyValue = -1
            var list: MutableList<SingleSelectBean> = ArrayList()
            var moneyList = mutableListOf<Int>()
            var showIndex = 0
            val creditLine: Int = selectProduct!!.creditLine
            var minApplyAmount: Int = selectProduct!!.minApplyAmount
            var calLoanAmount = 0
            if (appConfigBeanData != null) {
                calLoanAmount = appConfigBeanData!!.calLoanAmount.toInt()
                showMoneyValue = showMoney!!.toInt()
            }

            if (calLoanAmount == 0) {
                list.add(SingleSelectBean("$${creditLine}", "${creditLine}"))
            } else {
                val count: Int = ((creditLine - minApplyAmount) / calLoanAmount).toInt() + 1
                for (i in 0 until count) {
                    var value = (creditLine - calLoanAmount * i);
                    list.add(SingleSelectBean("$${StringUtils.formatNumberWithCommas(value.toString())}", "${value}"))
                    moneyList.add(value)
                }
                moneyList.forEachIndexed { index, money ->
                    if (showMoneyValue == money.toInt()) {
                        showIndex = index
                    }
                }
                val closestIndex = findClosestIndex(showMoneyValue, moneyList)

                if (closestIndex != null) {
                    showIndex = closestIndex
                }

                if (count == 0) {
                    list.add(SingleSelectBean("$${StringUtils.formatNumberWithCommas(creditLine.toString())}", "${creditLine}"))
                }
            }
            var selectPop = SingleSelectMomenyDialogView(
                this@MLoanActivity,
                it,
                "¿Cuánto quieres pedir prestado?"
            );
            selectPop.showSingleSelectDialog(this@MLoanActivity, list, showIndex)
            selectPop.setSingleSelectListener(object : SingleSelectListener {
                override fun checked(s: SingleSelectBean?) {
                    if (!s!!.code.isNullOrEmpty()){
                        Log.e("----s.code",s.code)
                        loancalLoan(selectProductInfo!!, s.code)
                    }
                }
            })
        }
        tv_mas.setOnClickListener {
            if (duracionPrestamoAdapter == null) {
                return@setOnClickListener;
            }
            runOnUiThread{
                try {
                    loadLoanData()
                    var selectProductDialog = SingleSelectProductDialogView(this@MLoanActivity, productSelectPosition)
                    selectProductDialog.showSingleSelectDialog(this@MLoanActivity, it)
                    selectProductDialog.setList(duracionPrestamoList)
                    selectProductDialog?.setItemClick { view, position ->
                        if ( duracionPrestamoList.size > 1 ){
                            loadLoanDataAgain()
                            selectDuracionPrestamoPosition(position)
                            duracionPrestamoAdapter?.selectPosition = 1
                            duracionPrestamoAdapter?.notifyDataSetChanged()
                        } else {
                            loadLoanDataAgain()
                            selectDuracionPrestamoPosition(0)
                            duracionPrestamoAdapter?.selectPosition = 0
                            duracionPrestamoAdapter?.notifyDataSetChanged()
                        }

                    }
                } catch (e:Exception){
                    e.printStackTrace()
                }
            }
        }

        tv_account_bank.setOnClickListener {
            tv_account_bank.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_loan_up,0)
            var selectProductBankDialog = SingleSelectBankDialogView(this@MLoanActivity)
            selectProductBankDialog.showSingleSelectDialog(this@MLoanActivity, it, object : JDialogCallback {
                override fun cancel(view: View?) {
                    tv_account_bank.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_loan_down,0)
                }

                override fun confirm(view: View?) {
                }
            })
            selectProductBankDialog.setList(accounts)
            selectProductBankDialog?.setItemClick(object : SingleSelectBankDialogView.onItemClickListener {
                override fun onItemClick(view: View?, position: Int) {
                    selectBank = accounts.get(position)
                    tv_account_bank.setText(StringUtils.keepLastFourDigits(selectBank?.accountNumber))
                }
            })
        }

        ll_all_money_tips.setOnClickListener {
            it.isSelected = if (it.isSelected) false else true
            if (it.isSelected) {
                ll_all_money.visibility = View.VISIBLE
                tv_have_money.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_loan_up,0)
            } else {
                ll_all_money.visibility = View.GONE
                tv_have_money.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_loan_down,0)
            }
        }

        tv_total_date_money.setOnClickListener {
            if (it.isSelected) {
                rvVoList.visibility = View.VISIBLE
                tv_total_date_money.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_loan_up,0)
            } else {
                rvVoList.visibility = View.GONE
                tv_total_date_money.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_loan_down,0)
            }
            it.isSelected = if (it.isSelected) false else true
        }
        tv_two_hide.setOnClickListener {
            fl_top_tips.visibility = View.GONE
        }
        fl_top_tips.setOnClickListener {
            if (fl_top_tips.visibility == View.VISIBLE) {
                fl_top_tips.visibility = View.GONE
            }
        }

        tv_terminos.setOnClickListener {
            val params: MutableMap<String, String> = java.util.HashMap()
//            showMyLoading()
            PermisosModle.instant.getZiLiPageWebLinkConfig(params, object : HttpCallback {
                override fun onSuccess(data: String) {
                    try {
                        var webLinkBean = GsonUtils.getGson().fromJson(data, WebLinkBean::class.java)
                        if (webLinkBean != null && webLinkBean.data != null) {
                            var intent = Intent(this@MLoanActivity, WebViewActivity::class.java)
                            var url = "${webLinkBean.data.termUse}"
                            LogUtils.logE("Mpay webLinkUrl: $url")
                            intent.putExtra("url", url)
                            startActivity(intent)
                        }
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
//                    hideMyLoading()
                }

                override fun onFaill(e: String) {
//                    hideMyLoading()
                }
            })
        }
        tv_politica.setOnClickListener {
            val params: MutableMap<String, String> = java.util.HashMap()
//            showMyLoading()
            PermisosModle.instant.getZiLiPageWebLinkConfig(params, object : HttpCallback {
                override fun onSuccess(data: String) {
                    try {
                        var webLinkBean = GsonUtils.getGson().fromJson(data, WebLinkBean::class.java)
                        if (webLinkBean != null && webLinkBean.data != null) {
                            var intent = Intent(this@MLoanActivity, WebViewActivity::class.java)
                            var url = "${webLinkBean.data.privacyPolicy}"
                            LogUtils.logE("Mpay webLinkUrl: $url")
                            intent.putExtra("url", url)
                            startActivity(intent)
                        }
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
//                    hideMyLoading()
                }

                override fun onFaill(e: String) {
//                    hideMyLoading()
                }
            })
        }

        cb.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked){
                PointMgr.sendEvent("cl_agree_privacy_click_gou")
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_agree_privacy_click_gou")
                btn_confirm.alpha = 1.0f
            }else{
                btn_confirm.alpha = 0.5f
            }
        }

    }

    fun convertThousandSeparatorToDouble(formattedNumber: String, pattern: String = "#,###.##"): Double? {
        require(!formattedNumber.isNullOrBlank()) { "Formatted number cannot be null or empty" }

        val decimalFormat = DecimalFormat(pattern)

        try {
            val parsedNumber = decimalFormat.parse(formattedNumber)
            return parsedNumber?.toDouble()
        } catch (e: NumberFormatException) {
            e.printStackTrace()
            return 0.toDouble()
        }
    }

    private fun initRecycler() {
        Log.e("---setFirst","set")
        recyclerView?.layoutManager = GridLayoutManager(this, 2)
        if (duracionPrestamoAdapter == null) {
            duracionPrestamoAdapter = DuracionPrestamoAdapter(this);

        }
        duracionPrestamoAdapter?.data = duracionPrestamoShowList
        recyclerView.adapter = duracionPrestamoAdapter
        duracionPrestamoAdapter?.itemClick = object : DuracionPrestamoAdapter.onItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                showVipTip(position)
            }
        }

        rvVoList?.layoutManager = LinearLayoutManager(this)
        if (loanInfoVoListAdapter == null) {
            loanInfoVoListAdapter = LoanInfoVoListAdapter(this);
        }
        loanInfoVoListAdapter?.data = loanInfoVoList
        rvVoList.adapter = loanInfoVoListAdapter
        loanInfoVoListAdapter?.itemClick = object : LoanInfoVoListAdapter.onItemClickListener {
            override fun onItemClick(view: View, position: Int) {

            }
        }

    }

    private fun showVipTip(position: Int) {
        var vip_tip = SharePreUtil.getStringData("vip_tip")
        if (TextUtils.isEmpty(vip_tip) && loanInfoVoListAdapter!!.selectPosition == 0) {
            var jvDialogView = JVipDialog(this, object : JDialogCallback {
                override fun cancel(view: View?) {
                }

                override fun confirm(view: View?) {
                    selectDuracionPrestamoPosition(position)
                }
            })
            SharePreUtil.saveStringData("vip_tip", "vip_tip")
            jvDialogView.show()
        } else {
            selectDuracionPrestamoPosition(position)
        }
    }

    private fun initEvent() {
        abBackIBtn.setOnClickListener {
            loanRetentionDialog?.showToDialog(this@MLoanActivity)
        }
    }


    fun InitLoad() {
        loadLoanData()
        bankgetBankAccountList()
        securitygetApplicationConfig();
    }

    var appConfigBeanData: AppConfigBeanData? = null
    private fun securitygetApplicationConfig() {
        var params: HashMap<String, String> = HashMap()
//        showMyLoading()
        mianModle?.securitygetApplicationConfig(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                println("")
                var appConfigBean: AppConfigBean =
                    GsonUtils.getGson().fromJson(data, AppConfigBean::class.java);
                if (appConfigBean != null) {
                    appConfigBeanData = appConfigBean?.data
                }
//                hideMyLoading()
            }

            override fun onFaill(e: String) {
//                hideMyLoading()
            }

        })
    }

    private fun loadLoanData() {
        if (result != null) {
            var data = result!!.getData();
            if (data != null) {
                var list = data!!.productInfoList
                if ( duracionPrestamoShowList.size > 0 ){
                    duracionPrestamoShowList.clear()
                }
                if ( duracionPrestamoList.size > 0 ){
                    duracionPrestamoList.clear()
                }
                if (list != null && list.size > 0) {
                    duracionPrestamoList?.addAll(list)
                    if (list.size > 2) {
                        val showList = list.subList(0,2)
                        duracionPrestamoShowList.addAll(showList)
                    } else {
                        duracionPrestamoShowList.addAll(list)
                    }
                }

                runOnUiThread {
                    duracionPrestamoList.add(CreditGetResultBean.DataBean.ProductInfoListBean())
                    duracionPrestamoShowList.add(CreditGetResultBean.DataBean.ProductInfoListBean())
                    for (i in 0..<duracionPrestamoShowList.size){
                        var data = GsonUtils.getGson().toJson(duracionPrestamoShowList.get(i))
                        Log.e("===duracionPrestamoShowList", data.toString())
                    }

                    duracionPrestamoAdapter?.notifyDataSetChanged()

                    selectDuracionPrestamoPosition(0)

                    if (duracionPrestamoList.isNotEmpty()) {
                        tv_loan_tip_day.text = "${duracionPrestamoList.get(0).totalLimitDays} Day en ${duracionPrestamoList.get(0).periods} Cuotas"

                        val z: Float = (duracionPrestamoList.get(0).totalRate * duracionPrestamoList.get(0).minApplyAmount).toFloat()
                        tv_loan_tip_money.text =
                            "Pide prestado $${
                                StringUtils.formatNumberWithCommas(duracionPrestamoList.get(0).minApplyAmount.toString())
                            }  y solo paga $ ${StringUtils.formatNumberWithCommas(z.toString())} de interés por día."
                    }
                }
            } else {
                finish()
            }
        } else {
            finish()
        }
    }

    private fun loadLoanDataAgain() {
        if (result != null) {
            var data = result!!.getData();
            if (data != null) {
                var list = data!!.productInfoList
                if ( duracionPrestamoShowList.size > 0 ){
                    duracionPrestamoShowList.clear()
                }
                if ( duracionPrestamoList.size > 0 ){
                    duracionPrestamoList.clear()
                }
                if (list != null && list.size > 1) {
                    val sharedPreferences: SharedPreferences = getSharedPreferences("ListChoose", MODE_PRIVATE)
                    val position = sharedPreferences.getString("ListChoose","")
                    duracionPrestamoList?.addAll(list)
                    if (position != null) {
//                        var changeProduct = duracionPrestamoList.get(1)
                        duracionPrestamoList.set(1, duracionPrestamoList.get(position.toInt()))
//                        duracionPrestamoList.set(position.toInt(), changeProduct)
                    }
                    if (list.size > 2) {
                        var showList: MutableList<CreditGetResultBean.DataBean.ProductInfoListBean> =
                            ArrayList()
                        showList.addAll(listOf(list[0]))
                        if ( position != null ){
                            showList.addAll(listOf(list[position.toInt()]))
                        }
                        duracionPrestamoShowList.addAll(showList)
                    } else {
                        duracionPrestamoShowList.addAll(list)
                    }
                } else {
                    if (list != null) {
                        duracionPrestamoShowList.addAll(list)
                    }
                }

                runOnUiThread {
                    duracionPrestamoList.add(CreditGetResultBean.DataBean.ProductInfoListBean())
                    duracionPrestamoShowList.add(CreditGetResultBean.DataBean.ProductInfoListBean())
                    for (i in 0..<duracionPrestamoShowList.size){
                        var data = GsonUtils.getGson().toJson(duracionPrestamoShowList.get(i))
                        Log.e("===duracionPrestamoShowList", data.toString())
                    }

                    duracionPrestamoAdapter?.notifyDataSetChanged()

                    if ( duracionPrestamoList.size > 2 ){
                        selectDuracionPrestamoPosition(1)
                    } else {
                        selectDuracionPrestamoPosition(0)
                    }


                    if (duracionPrestamoList.isNotEmpty()) {
                        tv_loan_tip_day.text = "${duracionPrestamoList.get(0).totalLimitDays} Day en ${duracionPrestamoList.get(0).periods} Cuotas"

                        val z: Float = (duracionPrestamoList.get(0).totalRate * duracionPrestamoList.get(0).minApplyAmount).toFloat()
                        tv_loan_tip_money.text =
                            "Pide prestado $${
                                StringUtils.formatNumberWithCommas(duracionPrestamoList.get(0).minApplyAmount.toString())
                            }  y solo paga $ ${StringUtils.formatNumberWithCommas(z.toString())} de interés por día."
                    }

                }
            } else {
                finish()
            }
        } else {
            finish()
        }
    }

    var selectProduct: CreditGetResultBean.DataBean.ProductInfoListBean? = null
    var productSelectPosition = 0
    private fun selectDuracionPrestamoPosition(position: Int) {
        duracionPrestamoAdapter?.selectPosition = position
        duracionPrestamoAdapter?.notifyDataSetChanged()

        productSelectPosition = position

        selectProduct = duracionPrestamoList.get(position);
        Log.e("|||selectProduct!!.creditLine", selectProduct!!.creditLine.toString())
        Log.e("|||selectProduct", GsonUtils.getGson().toJson(selectProduct))
        loancalLoan(selectProduct!!, selectProduct!!.creditLine.toString())
    }

    private fun bankgetBankAccountList() {
        val params: MutableMap<String, String> = java.util.HashMap()
//        showMyLoading()
        loanModle?.bankgetBankAccountList(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                try {
                    var bankAccountListBean =
                        GsonUtils.getGson().fromJson(data, BankAccountListBean::class.java);
                    if (bankAccountListBean == null) {
                        return;
                    }
                    runOnUiThread {
                        showBankAccountList(bankAccountListBean.data.accounts);
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
//                hideMyLoading()
            }

            override fun onFaill(e: String) {
//                hideMyLoading()
            }
        })
    }

    private var accounts: MutableList<BankAccountListBean.DataBean.AccountsBean> = ArrayList()
    private fun showBankAccountList(list: List<BankAccountListBean.DataBean.AccountsBean>) {

        if (accounts != null) {
            this.accounts = list.toMutableList();
            for ( i in 0..accounts.size-1 ){
                var select = GsonUtils.getGson().toJson(accounts.get(i))
                Log.e("---selset",select)
                var mySharedPreferences: SharedPreferences = getSharedPreferences("setSelectPhone", MODE_PRIVATE)
                val selectBank: String? = mySharedPreferences.getString("setSelectBank", "")
                val selsetPhone: String? = mySharedPreferences.getString("setSelectPhone", "")
                if (selectBank != null) {
                    Log.e("----selectBank",selectBank)
                };
                if ( selsetPhone!=null ){
                    Log.e("----selsetPhone",selsetPhone)
                    Log.e("----bank",accounts.get(i).bankName)
                    Log.e("----phone",accounts.get(i).accountNumber)
                    if ( accounts.get(i).accountNumber.contains(selsetPhone) && accounts.get(i).bankName.equals(selectBank) ){
                        val sharedPreferences: SharedPreferences =getSharedPreferences("setSelectPhone", MODE_PRIVATE)
                        val editor = sharedPreferences.edit()
                        editor.putString("setSelectPosition", i.toString())
                        editor.apply()
                        showBankAccountListPosition(i)
                        break
                    }
                }

                if ( i == accounts.size - 1 ){
                    val sharedPreferences: SharedPreferences =getSharedPreferences("setSelectPhone", MODE_PRIVATE)
                    val editor = sharedPreferences.edit()
                    editor.putString("setSelectPosition", "0")
                    editor.apply()
                    showBankAccountListPosition(0)
                }
            }
        }
    }

    private var selectBank: BankAccountListBean.DataBean.AccountsBean? = null;

    private fun showBankAccountListPosition(position: Int) {
        if (accounts.size > position) {
            selectBank = accounts.get(position)

            tv_account_bank.setText(StringUtils.keepLastFourDigits(selectBank?.accountNumber))
        }
    }

    private var selectProductInfo: CreditGetResultBean.DataBean.ProductInfoListBean? = null
    private fun loancalLoan(
        data: CreditGetResultBean.DataBean.ProductInfoListBean,
        applyAmount: String
    ) {
        Log.e("|||app1",applyAmount)
        selectProductInfo = data;
        val moneyText = StringUtils.formatNumberWithCommas(applyAmount)
//        tv_money?.text = moneyText
        tv_money.setAmount(applyAmount.toFloat(), true)
        tv_tips_money.text = moneyText
        val params: MutableMap<String, String> = java.util.HashMap()
        try {
            params["productId"] = data.productId!!
            params["applyAmount"] = applyAmount
            params["groupId"] = data.groupId!!
            params["reqId"] = preReqId
            params["productIndex"] = data.productIndex.toString()
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        Log.e("|||productId",data.productId.toString())
        Log.e("|||applyAmount",applyAmount)
        Log.e("|||groupId",data.groupId.toString())
        Log.e("|||reqId",preReqId)
        Log.e("|||productIndex",data.productIndex.toString())
//        showMyLoading()
        loanModle?.loancalLoan(params, object : HttpCallback {
            @RequiresApi(Build.VERSION_CODES.O)
            override fun onSuccess(data: String) {
                try {
                    var dataBean =
                        GsonUtils.getGson().fromJson(data, LoanCalLoanDataBean::class.java)
                    runOnUiThread {
                        showLoanCalLoan(dataBean);
                    }
                    Log.e("----data",data)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
//                hideMyLoading()
            }

            override fun onFaill(e: String) {
//                hideMyLoading()
            }
        })
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun showLoanCalLoan(data: LoanCalLoanDataBean) {
        loanInfoVoList.clear()
        //这里先预设数值防止加载错误导致出错
        val setMoney: String = selectProduct!!.creditLine.toFloat().extFormatMoney()
        tv_have_money.text = "$${setMoney}"
        tv_total_money.text = "$${setMoney}"
        tv_lixi.text = "$0"
        if ( tv_date.text.equals("") || tv_date.text == null ){
            tv_date.text = "1.er Pago ${changeDate(time)}"
            tv_total_date_money.setText("$${StringUtils.formatNumberWithCommas(money)}")
        }

        if (data != null) {
            var dataBean = data.data
            if (dataBean != null) {
                Log.e("----dataBean",GsonUtils.getGson().toJson(dataBean))
                tv_have_money.text = "$${StringUtils.formatNumberWithCommas(dataBean.totalReceiveAmount)}"
                tv_total_money.text = "$${StringUtils.formatNumberWithCommas(dataBean.applyAmount.toString())}"
                tv_lixi.text = "$${StringUtils.formatNumberWithCommas(dataBean.totalPreFeeAmount)}"

                var loanInfoVoList = data.data.loanInfoVoList
                if (loanInfoVoList != null && loanInfoVoList.size > 0) {
                    var loanModle = loanInfoVoList.get(0)
                    if (loanModle != null) {
                        tv_date.setText("1.er Pago ${changeDate(loanModle.dueDate)}")
                        var rightList = GsonUtils.getGson().toJson( loanModle)
                        Log.e("===rightList",rightList)
                        tv_total_date_money.setText("$${StringUtils.formatNumberWithCommas(loanModle.totalRepayAmount.toString())}")
                    }
                    this.loanInfoVoList.addAll(loanInfoVoList)
                }
            }
        }
        loanInfoVoListAdapter?.notifyDataSetChanged()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun DateCalculator( days:Int): String {

        val currentDate = LocalDate.now()
        val formatter = DateTimeFormatter.ofPattern("yyyyMMdd")
        val formattedDate = currentDate.format(formatter)

        var calendar: Calendar = Calendar.getInstance()
        calendar.set(Calendar.YEAR, Integer.parseInt(formattedDate.substring(0, 4)))
        calendar.set(Calendar.MONTH, Integer.parseInt(formattedDate.substring(4, 6)) - 1)
        calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(formattedDate.substring(7)))

        calendar.add(Calendar.DAY_OF_MONTH, days)

        val endDate: Date = calendar.time

        val sdf = SimpleDateFormat("dd-MM-yyyy")
        val formattedEndDate: String = sdf.format(endDate)

        return formattedEndDate
    }



    private fun loanapplyLoan(applyAmount: String) {
        Log.e("|||app2",applyAmount)
        Log.e("|||productId",selectProductInfo!!.productId.toString())
        Log.e("|||applyAmount",applyAmount)
        Log.e("|||groupId",selectProductInfo!!.groupId.toString())
        Log.e("|||reqId",preReqId)
        Log.e("|||productIndex",selectProductInfo!!.productIndex.toString())
        val params: MutableMap<String, String> = java.util.HashMap()

        params["productId"] = selectProductInfo!!.productId!!
        params["applyAmount"] = applyAmount
        params["groupId"] = selectProductInfo!!.groupId!!
        params["reqId"] = preReqId
        params["productIndex"] = selectProductInfo!!.productIndex.toString()

        try {
            if (!SPUtils.getPhone().isNullOrEmpty()) {
                params["mobile"] = SPUtils.getPhone()!!
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }

        params["bankAccountNo"] = selectBank!!.accountNumber
        params["accountId"] = selectBank!!.accountId


        LogUtils.logE("kelvin --loanapplyLoan-params:-${GsonUtils.getGson().toJson(params)}")
//        showMyLoading()
        loanModle?.loanapplyLoan(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                try {
                    try {
                        val jsonObject: JSONObject = JSONObject(data)
                        if (TextUtils.equals(
                                "000",
                                jsonObject.optString("code")
                            ) || TextUtils.equals("0000", jsonObject.optString("code"))
                        ) {
                            PointMgr.sendEvent("cl_sutbmit_loan_yes")
                            Log.e("PointMgr.INSTANCE.sendEvent", "cl_sutbmit_loan_yes")
                            getZiLiPageWebLinkConfig()
                            requestsubRestShortMsgInfo()
                        } else {
                            runOnUiThread {
                                PointMgr.sendEvent("cl_sutbmit_loan_no")
                                Log.e("PointMgr.INSTANCE.sendEvent", "cl_sutbmit_loan_no")
                                Toast.makeText(
                                    this@MLoanActivity,
                                    jsonObject.optString("msg"),
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
//                hideMyLoading()
            }

            override fun onFaill(e: String) {
//                hideMyLoading()
            }
        })
    }

    fun requestsubRestShortMsgInfo() {
        lifecycleScope.launch(Dispatchers.Main){
            var sList = async { ZhiliDeviceUtils.getsList3000(this@MLoanActivity) }.await()
            LogUtils.logE("-00--size--${sList?.size}")
            if (sList != null && !sList.isNullOrEmpty()){
                var sCount = SPUtils.getInt("smsCount")
                var sMaxCount = SPUtils.getInt("smsMaxCount")
                LogUtils.logE("---smsCount--$sCount")
                LogUtils.logE("---smsMaxCount--$sMaxCount")
                var size = sList?.size
                if (size!! > sCount!!){
                    if (size > sMaxCount!!){
                        size = sMaxCount
                    }
                    sList = sList.subList(sCount, size!!)
                }
                var allSize = sList?.size
//                var count = allSize!! / smsCount!!
//                if (allSize!! % smsCount!! > 0){
//                    count++
//                }
                var shortS = allSize?.let { sList.subList(0, it) }
                val params: MutableMap<String, Any> = HashMap()
                if (shortS != null) {
                    params.put("shortMsg", shortS)
                }
//                showMyLoading()
                MianModle.instant.subRestShortMsgInfo(params, object : HttpCallback{
                    override fun onSuccess(data: String) {
                        LogUtils.logE(" kelvin --shortMsg--data:$data")
//                        hideMyLoading()
                    }

                    override fun onFaill(e: String) {
                        LogUtils.logE(" kelvin --shortMsg--onFaill:$e")
//                        hideMyLoading()
                    }

                })
//                for (index in 0..count){
//                    if (index != count - 1){
//                        var shortSms = smsList!!.subList(smsCount * index, smsCount * (index + 1))
//                        val params: MutableMap<String, Any> = HashMap()
//                        params.put("shortMsg", shortSms)
//                        showMyLoading()
//                        MianModle.instant.submitRestShortMsgInfo(params, object : HttpCallback{
//                            override fun onSuccess(data: String) {
//                                LogUtils.logE(" ----kelvin --shortMsg--data:$data")
//                                hideMyLoading()
//                            }
//
//                            override fun onFaill(e: String) {
//                                LogUtils.logE(" kelvin --shortMsg--onFaill:$e")
//                                hideMyLoading()
//                            }
//
//                        })
//                    }else{
//                        var shortSms = smsList!!.subList(smsCount * index, allSize)
//                        val params: MutableMap<String, Any> = HashMap()
//                        params.put("shortMsg", shortSms)
//                        showMyLoading()
//                        MianModle.instant.submitRestShortMsgInfo(params, object : HttpCallback{
//                            override fun onSuccess(data: String) {
//                                LogUtils.logE(" kelvin --shortMsg--data:$data")
//                                hideMyLoading()
//                            }
//
//                            override fun onFaill(e: String) {
//                                LogUtils.logE(" kelvin --shortMsg--onFaill:$e")
//                                hideMyLoading()
//                            }
//
//                        })
//                    }
//                }
            }
        }

    }


    fun getZiLiPageWebLinkConfig() {
        val params: MutableMap<String, String> = java.util.HashMap()
//        showMyLoading()
        PermisosModle.instant.getZiLiPageWebLinkConfig(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                try {
                    var webLinkBean = GsonUtils.getGson().fromJson(data, WebLinkBean::class.java)
                    if (webLinkBean != null && webLinkBean.data != null) {
                        runOnUiThread {
                            var isLoanOperation = SPUtils.getString("isLoanOperation")
                            if (StringUtils.isEmpty(isLoanOperation)){
                                SPUtils.put("isLoanOperation","true")
                            }
                            var intent = Intent(this@MLoanActivity, WebViewActivity::class.java)
                            intent.putExtra("url", webLinkBean.data.applyResult)
                            startActivity(intent)
                            getCanApply = true
                            finish()
                        }
                    }
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
//                hideMyLoading()
            }

            override fun onFaill(e: String) {
//                hideMyLoading()
            }
        })
    }

    class DuracionPrestamoAdapter(context: Context?) :
        RecyclerView.Adapter<DuracionPrestamoAdapter.ViewHolder>() {

        var mContext: Context? = context;
        var data: MutableList<CreditGetResultBean.DataBean.ProductInfoListBean> = ArrayList()
        var selectPosition = 0
        lateinit var listener: OnItemClickListener

        public fun setOnItemClickListener(listener: OnItemClickListener) {
            this.listener = listener
        }

        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var ll_item = itemView.findViewById<LinearLayout>(R.id.ll_item)
            var ll_child = itemView.findViewById<LinearLayout>(R.id.ll_child)
            var tv_day = itemView.findViewById<TextView>(R.id.tv_day)
            var tv_tip = itemView.findViewById<TextView>(R.id.tv_tip)
            var iv_vip = itemView.findViewById<ImageView>(R.id.iv_vip)
            var iv_lock = itemView.findViewById<ImageView>(R.id.iv_lock)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val itemView: View = LayoutInflater.from(mContext)
                .inflate(R.layout.adapter_duracion_prestamo, parent, false)
            return ViewHolder(itemView)
        }

        override fun getItemCount(): Int {
            return data.size;
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val item = data.get(position)
            Log.e("|||item", GsonUtils.getGson().toJson(item))
//            var data: MutableList<CreditGetResultBean.DataBean.ProductInfoListBean> = ArrayList()

            Log.e("|||item.totalLimitDays",item.totalLimitDays.toString())
            Log.e("|||item.periods",item.periods.toString())
            Log.e("|||StringUtils.formatNumberWithCommas(item.minApplyAmount.toString())",StringUtils.formatNumberWithCommas(item.minApplyAmount.toString()))
            Log.e("|||StringUtils.formatNumberWithCommas(z.toString())",StringUtils.formatNumberWithCommas((item.totalRate * item.minApplyAmount).toFloat().toString()))

            val typefaceName = Typeface.createFromAsset(mContext!!.assets, "Poppins-SemiBold.ttf")
            holder.tv_day.typeface = typefaceName
            if (position == data.size - 1) {
                holder.ll_item.setBackgroundResource(R.drawable.btn_select_loan_bg_lock)
                holder.ll_child.setBackgroundResource(0)
                holder.tv_day.setText("120 Day en 4 Cuotas")
                holder.tv_tip.setText("Pegue puntualmente para desbloquear mejor condiciones.")
                holder.iv_lock.visibility = View.VISIBLE
                holder.iv_vip.visibility = View.GONE
            } else {
                holder.ll_item.setBackgroundResource(R.drawable.btn_selector_loan)
                holder.ll_child.setBackgroundResource(R.drawable.btn_select_loan_bg_white)

                holder.ll_item.isSelected = position == selectPosition

                holder.iv_lock.visibility = View.GONE

                holder.iv_vip.visibility = if (position == 0) View.VISIBLE else View.GONE

                holder.tv_day.setText("${item.totalLimitDays} Day en ${item.periods} Cuotas")
                val z: Float = (item.totalRate * item.minApplyAmount).toFloat()
                Log.e("===totalRate", item.totalRate.toString())
                Log.e("===minApplyAmount", item.minApplyAmount.toString())

                holder.tv_tip.text =
                    "Pide prestado $${
                        StringUtils.formatNumberWithCommas(item.minApplyAmount.toString())
                    }  y solo paga $ ${StringUtils.formatNumberWithCommas(z.toString())} de interés por día."
            }
            holder.ll_item.setOnClickListener {

                if (position != data.size - 1) {
                    itemClick?.onItemClick(it, position)
                    Log.e("----position",position.toString())
                }
            }
            if ( position == 0 ){
                holder.ll_child.post {
                    var itemLeft = holder.ll_child.left.toString()
                    var itemRight = holder.ll_child.right.toString()
                    var itemTop = holder.ll_child.top.toString()
                    var itemBottom = holder.ll_child.bottom.toString()
                    SharePreUtil.saveStringData("loan_itemLeft", itemLeft)
                    SharePreUtil.saveStringData("loan_itemRight", itemRight)
                    SharePreUtil.saveStringData("loan_itemTop", itemTop)
                    SharePreUtil.saveStringData("loan_itemBottom", itemBottom)
                    Log.e("----view1",itemLeft)
                    Log.e("----view1",itemRight)
                    Log.e("----view1",itemTop)
                    Log.e("----view1",itemBottom)
                }
            }
        }

        var itemClick: onItemClickListener? = null

        interface onItemClickListener {
            fun onItemClick(view: View, position: Int)
        }
    }

    class LoanInfoVoListAdapter(context: Context?) :
        RecyclerView.Adapter<LoanInfoVoListAdapter.ViewHolder>() {

        var mContext: Context? = context;

        var data: MutableList<LoanInfoVo> = ArrayList()

        var selectPosition = 0

        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var tvIndex = itemView.findViewById<TextView>(R.id.tvIndex)
            var tvDate = itemView.findViewById<TextView>(R.id.tvDate)
            var tvMoney = itemView.findViewById<TextView>(R.id.tvMoney)
            var rvChild = itemView.findViewById<RecyclerView>(R.id.rvChild)
            var ll_item = itemView.findViewById<LinearLayout>(R.id.ll_item)
            var imgSelected = itemView.findViewById<ImageView>(R.id.img_select)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val itemView: View = LayoutInflater.from(mContext)
                .inflate(R.layout.adapter_loan_info_volist, parent, false)
            return ViewHolder(itemView)
        }

        override fun getItemCount(): Int {
            return data.size;
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            var item = data.get(position)
            holder.tvIndex.setText("${position + 1}")
            holder.tvDate.setText("${changeDate(item.dueDate)}")
            holder.tvMoney.setText("$${StringUtils.formatNumberWithCommas(item.currentPeriodTotalSurplusAmount.toString())}")

            holder.rvChild.layoutManager = LinearLayoutManager(mContext)
            var adapter: LoanInfoVoListChildAdapter = LoanInfoVoListChildAdapter(mContext);
            var list: MutableList<LoanInfoVoChild> = ArrayList()
            var fieldsMap = item.fieldsMap;
            if (fieldsMap != null) {
                for (key in fieldsMap.keys) {
                    var value = fieldsMap[key]
                    list.add(value?.let { LoanInfoVoChild(key, it) }!!)
                }
            }
            adapter.data = list
            holder.rvChild.adapter = adapter

            holder.ll_item.setOnClickListener {
                PointMgr.sendEvent("cl_period_click_zhouqitime")
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_period_click_zhouqitime")
                it.isSelected = if (it.isSelected) false else true
                if (it.isSelected) {
                    holder.rvChild.visibility = View.VISIBLE
                    holder.imgSelected.setImageResource(R.drawable.ic_loan_up)
                } else {
                    holder.rvChild.visibility = View.GONE
                    holder.imgSelected.setImageResource(R.drawable.ic_loan_down)
                }
            }


        }

        var itemClick: onItemClickListener? = null

        interface onItemClickListener {
            fun onItemClick(view: View, position: Int)
        }

        fun changeDate(date: String): String{
            var char: Char
            var finString = StringBuffer()
            var stringShow: String
            for ( index in 8..9 ){
                char = date.get(index)
                finString.append(char)
            }
            finString.append("-")
            for ( index in 5..6 ){
                char = date.get(index)
                finString.append(char)
            }
            finString.append("-")
            for ( index in 0..3 ){
                char = date.get(index)
                finString.append(char)
            }
            stringShow = finString.toString()
            return stringShow
        }
    }

    class LoanInfoVoListChildAdapter(context: Context?) :
        RecyclerView.Adapter<LoanInfoVoListChildAdapter.ViewHolder>() {

        var mContext: Context? = context;

        var data: MutableList<LoanInfoVoChild> = ArrayList()

        var selectPosition = 0

        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var tvTitle = itemView.findViewById<TextView>(R.id.tvTitle)
            var tvMoney = itemView.findViewById<TextView>(R.id.tvMoney)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val itemView: View = LayoutInflater.from(mContext)
                .inflate(R.layout.adapter_loan_info_volist_child, parent, false)
            return ViewHolder(itemView)
        }

        override fun getItemCount(): Int {
            return data.size;
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            var item = data.get(position)
            holder.tvTitle.setText("${item.title}")
            holder.tvMoney.setText("$${StringUtils.formatNumberWithCommas(item.money)}")
            Log.e("----title", item.title)
            Log.e("----money", item.money)
        }

        var itemClick: onItemClickListener? = null

        interface onItemClickListener {
            fun onItemClick(view: View, position: Int)
        }
    }

    fun findClosestIndex(target: Int, numbers: List<Int>): Int? {
        if (numbers.isEmpty()) {
            return null
        }

        var closestNumber = numbers[0]
        var minDifference = Math.abs(target - closestNumber)
        var closestIndex = 0

        for ((index, number) in numbers.withIndex()) {
            val difference = Math.abs(target - number)
            if (difference < minDifference) {
                minDifference = difference
                closestNumber = number
                closestIndex = index
            }
        }

        return closestIndex
    }

    public override fun onStop() {
        super.onStop()
//        hideMyLoading()
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(true)
        var loan_itemLeft = SharePreUtil.getStringData("loan_itemLeft")
        var loan_itemRight = SharePreUtil.getStringData("loan_itemRight")
        var loan_itemTop = SharePreUtil.getStringData("loan_itemTop")
        var loan_itemBottom = SharePreUtil.getStringData("loan_itemBottom")
        Log.e("---loan_itemLeft",loan_itemLeft)
        Log.e("---loan_itemRight",loan_itemRight)
        Log.e("---loan_itemTop",loan_itemTop)
        Log.e("---loan_itemBottom",loan_itemBottom)
        val location = IntArray(2)
        recyclerView.getLocationOnScreen(location)
        Log.e("---loanrecy1",location[0].toString())
        Log.e("---loanrecy2",location[1].toString())
        val item = recyclerView.getChildAt(0).width
        val item2 = recyclerView.getChildAt(0).height
        Log.e("---loanrecy3",item.toString())
        Log.e("---loanrecy4",item2.toString())
        val layoutParams = tip_framelayout.getLayoutParams() as FrameLayout.LayoutParams
        layoutParams.topMargin = location[1] + loan_itemTop.toInt() - 2 // 新的顶部边距
        layoutParams.leftMargin = location[0] + loan_itemLeft.toInt() - 3 // 新的左边边距
        layoutParams.width = item + 6
        layoutParams.height = item2 + 26
        Log.e("---loantop1",layoutParams.topMargin.toString())
        Log.e("---loantop1",layoutParams.leftMargin.toString())
        Log.e("---loantop1",layoutParams.width.toString())
        Log.e("---loantop1",layoutParams.height.toString())
        tip_framelayout.setLayoutParams(layoutParams) // 应用新的布局参数

        val layoutParams2 = tip_framelayout2.getLayoutParams() as FrameLayout.LayoutParams
        layoutParams2.topMargin = 13// 新的顶部边距
        layoutParams2.leftMargin = 10 // 新的左边边距
        layoutParams2.width = item - 28
        layoutParams2.height = item2 - 16
        Log.e("---loantop2",layoutParams2.topMargin.toString())
        Log.e("---loantop2",layoutParams2.leftMargin.toString())
        Log.e("---loantop2",layoutParams2.width.toString())
        Log.e("---loantop2",layoutParams2.height.toString())
        tip_framelayout2.setLayoutParams(layoutParams2) // 应用新的布局参数

        val layoutParams3 = tip_framelayout3.getLayoutParams() as LinearLayout.LayoutParams
        layoutParams3.topMargin = 2 // 新的顶部边距
        layoutParams3.leftMargin = 2 // 新的左边边距
        layoutParams3.width = item - 32
        layoutParams3.height = item2 - 18
        Log.e("---loantop3",layoutParams3.topMargin.toString())
        Log.e("---loantop3",layoutParams3.leftMargin.toString())
        Log.e("---loantop3",layoutParams3.width.toString())
        Log.e("---loantop3",layoutParams3.height.toString())
        tip_framelayout3.setLayoutParams(layoutParams3) // 应用新的布局参数

        var tipValue = SharePreUtil.getStringData("loan_tip")
        fl_top_tips.visibility = View.VISIBLE
        if (TextUtils.isEmpty(tipValue)) {
            SharePreUtil.saveStringData("loan_tip", "ShowTipFinish:$phone")
            fl_top_tips.visibility = View.VISIBLE
            tv_one_hide.setOnClickListener {
                fl_one_tips.visibility = View.GONE
                fl_two_tips.visibility = View.VISIBLE
                var loan_itemLeft = SharePreUtil.getStringData("loan_itemLeft")
                var loan_itemRight = SharePreUtil.getStringData("loan_itemRight")
                var loan_itemTop = SharePreUtil.getStringData("loan_itemTop")
                var loan_itemBottom = SharePreUtil.getStringData("loan_itemBottom")
                Log.e("loan_itemLeft",loan_itemLeft)
                Log.e("loan_itemRight",loan_itemRight)
                Log.e("loan_itemTop",loan_itemTop)
                Log.e("loan_itemBottom",loan_itemBottom)
            }
        } else if ( tipValue.equals("justShowTip1:$phone") ){
            SharePreUtil.saveStringData("loan_tip", "ShowTipFinish:$phone")
            fl_top_tips.visibility = View.VISIBLE
            tv_one_hide.setOnClickListener {
                fl_one_tips.visibility = View.GONE
                fl_top_tips.visibility = View.GONE
            }
        }else{
            fl_top_tips.visibility = View.GONE
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        PointMgr.sendEvent("cl_credit_result_page_tuichu")
        Log.e("PointMgr.INSTANCE.sendEvent", "cl_credit_result_page_tuichu")
    }

    override fun hideLoading() {
    }

    override fun showLoading(msg: String?) {
    }

    companion object {
        var result: CreditGetResultBean? = null
        var reqId: String? = null
    }
}
